<?php defined('SYSPATH') or die('No direct script access.');

class Controller_BoAds extends Controller_BoBase {
	public $auth_required = TRUE;

	public function action_index()
	{
		$view = View::factory("pages/bo/home");
		$this->setTab($view);
		$this->baseInfo($view);
		$this->request->response = $view;
	}

	public function action_insertPage(){
		$view = View::factory("pages/bo/ads_add_page");
		$typeArray = array("网页广告","推荐商家");
		$view->set_global('typeArray', $typeArray);
		exit($view->render());
	}

	public function action_insert(){
		ORM::factory("ads")->insert($_POST);
		Request::$instance->redirect("boAds");
	}

	public function action_updatePage(){
		$ads = ORM::factory("ads",$_GET["adsid"]);
		$view = View::factory("pages/bo/ads_edit_page");
		$typeArray = array("网页广告","推荐商家");
		$view->set_global('typeArray', $typeArray);
		$view->result = $ads;
		exit($view->render());
	}

	public function action_update(){
		ORM::factory("ads",$_POST["id"])->update($_POST);
		Request::$instance->redirect("boAds");
	}

	public function action_show(){
		$view = View::factory("pages/bo/ads_page");
		$this->setTab($view);
		$this->baseInfo($view);
		exit($view->render());
	}

	public function action_search(){
		$categoryType = $_GET["categoryType"];
		$searchText = $_GET["searchText"];

		$view = View::factory("pages/bo/ads_page");

		$ads = ORM::factory("ads");
		$ads = $ads->where("status","=","A");
		if(!empty($searchText)){
			$ads = $ads->where($categoryType,"like","%".$searchText."%");
			$view->set_global('result_search_text',$searchText);
		}
		if(array_key_exists("page", $_GET)){
			$page = $_GET["page"];
		}
		$tmp = clone $ads;
		$count = $tmp->count_all();

		$pagination = Pagination::factory(array(
	  		'total_items'    => $count,
		));

		$result_ads = $ads->order_by('id','DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->find_all();

		$view->set_global('result_ads', $result_ads);

		$view->tab = 'ads';

		$page_links = $pagination->render();
		$view->set_global('page_links', $page_links);
		exit($view->render());
	}

	public function action_deleteAll(){
		if(ORM::factory("ads")->deleteAll($_POST["ids"])){
			$view = View::factory("pages/bo/common/message_dialog");
			$view->message = "删除成功";
			exit($view->render());
		}
	}

	private function baseInfo($view){
		$ads = ORM::factory("ads");
		$count = $ads->where("status","=","A")->count_all();
		$pagination = Pagination::factory(array(
	  		'total_items'    => $count,
		));
		$result_ads = $ads->where("status","=","A")->order_by('id','DESC')->limit($pagination->items_per_page)->offset($pagination->offset)->find_all();

		$view->set_global('result_ads', $result_ads);

		$page_links = $pagination->render();
		$view->set_global('page_links', $page_links);
	}

}
